#pragma once
#include <functional>
#include <vector>
#include <thread>
#include <mutex>
#include <atomic>
#include <condition_variable>
#include <queue>
#include <opencv2/opencv.hpp>
#include <nlohmann/json.hpp>


extern "C" {
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavutil/imgutils.h>
}

#include "decoder/common/thread_safe_queue.hpp"
#include "decoder/stream_decoder_worker.hpp"
#include "decoder/subtitle_decoder_worker.hpp"

using json = nlohmann::json;
namespace WD {

class FrameDecoder {
public:
    using FrameCallback = std::function<void(const FrameWithTimestamp&)>;
    using SubtitleCallback = std::function<void(const SubtitleInfo&)>;

    explicit FrameDecoder(const std::string& url,const int max_streams = 4);
    ~FrameDecoder();

    void start();
    void stop();
    
    void setSubtitleCallback(const SubtitleCallback& cb);
    // 设置特定流的回调函数
    // 这里的 stream_index 是从 0 开始的索引
    // 例如，0 表示第一个视频流，1 表示第二个视频
    void setStreamCallback(int stream_index, const FrameCallback& cb);
    void setStitchedFrameCallback(const FrameCallback& cb);

private:
    void readLoop();

    // 输入地址
    std::string input_url_;
    int max_streams_ = 4;  // 需要处理的最大流数
    AVFormatContext* fmt_ctx_ = nullptr;

    // 多线程相关
    std::thread decode_thread_;
    std::thread subtitle_thread_;
    std::atomic<bool> running_{false};
    FrameCallback stitched_frame_cb_;
    SubtitleCallback subtitle_cb_;
    std::map<int, FrameCallback> stream_callbacks_;  // 每个 stream 的独立回调

    std::map<int, std::shared_ptr<ThreadSafeQueue<AVPacket*>>> pkt_queues_;
    std::vector<std::unique_ptr<StreamDecoderWorker>> workers_; 
    std::vector<std::unique_ptr<SubtitleDecoderWorker>> subtitle_workers_;

    const int kSubtitleStreamIndex = 0; // 字幕流索引 (修正为 streams[0])

};

}  // namespace WD
